<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue';
import API from '@/services'
import { EDicType, EIndicatorStatus } from '@/utils/constants';
import {
  IconCaretDown
} from '@arco-design/web-vue/es/icon';
const props = withDefaults(
  defineProps<{
    modelValue: any;
    fieldPath: string;
  }>(),
  {
    // tableDisabled: false,
    // disableRemove: false
  }
);
const supportDimensionOV = ref<any>([])
const timePeriodList = ref<any>([])
const levelMericsOption :any = ref([])

const dimensionData:any=ref()
// 支持维度下拉框的loading
const loading:any = ref(false)
// 统计粒度
const periodLoading:any=ref(false)

const metricsTabsName:any = ref()



/* 统计粒度 */
const getTimePeriodList = async (cnName?: string) => {
    periodLoading.value = true
    try {
    const { code, data } = await API.timePeriod.getTimePeriodNameHint({
        cnName
    });
    if (code === 200 && Array.isArray(data)) {
        timePeriodList.value = data;
    }
    periodLoading.value = false
    } catch (error) {
        periodLoading.value = false
        console.log(error);
    }
};
/* 指标等级 */
const getGradeList = async () => {
    try {
    const { code, data } =
        await API.dictionaryConfig.getDictionaryConfigEnumTypeByEnumType({
        enumType: EDicType.grade
        });
    if (code === 200 && Array.isArray(data)) {
        levelMericsOption.value = data;
    }
    } catch (error) {
    console.log(error);
    }
};
/* 获取支持维度下拉列表 */
const getDimensionList = async (cnName?: string) => {
    loading.value = true
    try {
    const { code, data } = await API.dimension.getDimensionHintName({
        cnName
    });
    if (code === 200 && Array.isArray(data)) {
        supportDimensionOV.value = data;
    }
    loading.value = false
    } catch (error) {
    loading.value = false
    console.log(error);
    }
};
// 指标维度远端搜索
const handleSearch = (cnName:any) => {
    getDimensionList(cnName)
}

// 统计粒度远端搜索
const handlePeriodSearch = (cnName:any) => {
    getTimePeriodList(cnName)
}

const handleFiledName = async (metricsName:any, id:any) => {
    try {
        const { code } = await API.demand.postDetailCheckMetricsName({
            metricsName,
            detailId: id || null
        })
        if (code != 200) {
            metricsTabsName.value = true
        } else {
            metricsTabsName.value = false
        }
    } catch (error) {
        console.log(error)
    }
    
}
// 校验指标是否重名
const FieldRepeatName = (value:any, callback:any) => {
    if (!value) {
        callback('请输入指标名称');
    } else
    if (metricsTabsName.value) {
        callback('指标名称有重名，请重新输入');
    }
    else {
        callback();
    }
}

onMounted(() => {
    getTimePeriodList()
    getGradeList()
    getDimensionList()
})

watch(
    ()=>props.modelValue,
    (val) => {
        dimensionData.value = val
        // 支持维度回显值转数字类型
        if (typeof(val?.supportDimension) == 'string') {
           dimensionData.value.supportDimension = val.supportDimension.split(',')?.map(
                ((item:any)=>{
                    return Number(item)
                })
            ) 
        }
        // 统计粒度多选回显
        if (typeof(val?.timePeriod) == 'string') {
            dimensionData.value.timePeriod = val.timePeriod.split(',')?.map(
                ((item:any)=>{
                    return Number(item)
                })
            ) 
        }
        // 指标等级回显值转为数字类型
        if (typeof(val?.metricsLevel) == 'number') {
            dimensionData.value.metricsLevel = String(val.metricsLevel)
        }
    },
    {
        immediate: true
    }
)
</script>

<template>
    <a-form-item 
        show-colon
        :field="`${fieldPath}.metricsName`"
        label="指标名称"
        :rules="[{required:true, validator: FieldRepeatName}]"
    >
    <a-input 
        v-model.trim="dimensionData.metricsName" 
        placeholder="请输入指标具体中文名称，如：当月不含退款订单量"
        @change="handleFiledName(dimensionData.metricsName, dimensionData.id)"
    />
    
    </a-form-item>
    <a-form-item 
        show-colon
        :field="`${fieldPath}.description`"
        label="业务含义"
        required
        :rules="[{required:true,message:'请输入业务含义'}]"
    >
        <a-textarea 
            v-model="dimensionData.description" 
            placeholder="请尽可能详细的描述指标的含义、口径细节、计算公式等信息。如：统计自然月内，剔除退款订单后的订单量；"
        />
    </a-form-item>
    <a-form-item 
        show-colon
        :field="`${fieldPath}.supportDimension`"
        label="可用维度"
        required
        :rules="[{required:true,message:'请选择支持维度'}]"
    >
        <a-select 
            v-model="dimensionData.supportDimension" 
            placeholder="请选择"
            :loading="loading"
            allow-search
            allow-clear
            multiple
            :filter-option="false"

            @search="handleSearch"
            @popup-visible-change="(val:any) => {
                if (!val) {
                    getDimensionList()
                }
            }"
        >
            <template #arrow-icon>
                <icon-caret-down />
            </template>
            <a-option 
                v-for="item of supportDimensionOV" 
                :label="item.cnName" 
                :value="item.id"
            >
            </a-option>
        </a-select>
    </a-form-item>
    <a-form-item 
        show-colon
        :field="`${fieldPath}.timePeriod`"
        label="统计粒度"
        required
        :rules="[{required:true,message:'请选择统计粒度'}]"
    >
        <a-select 
            v-model="dimensionData.timePeriod" 
            placeholder="请选择"
            :loading="periodLoading"
            allow-search
            allow-clear
            :filter-option="false"
            @search="handlePeriodSearch"
            multiple
            @popup-visible-change="(val:any) => {
                if (!val) {
                    getTimePeriodList()
                }
            }"
        >
            <template #arrow-icon>
                <icon-caret-down />
            </template>
            <a-option 
                v-for="item of timePeriodList" 
                :label="item.cnName" 
                :value="item.id">
                
            </a-option>
        </a-select>
    </a-form-item>
    <a-form-item 
        show-colon
        :field="`${fieldPath}.metricsLevel`"
        label="指标等级"
    >
        <a-select 
            v-model="dimensionData.metricsLevel" 
            placeholder="请选择"

            class="w270"
            :options="levelMericsOption"
            allow-clear
        >
            <template #arrow-icon>
                <icon-caret-down />
            </template>
            
        </a-select>
    </a-form-item>
    <a-form-item 
        show-colon
        :field="`${fieldPath}.remarks`"
        label="备注"
    >
        <a-textarea 
            
            v-model="dimensionData.remarks" 
            placeholder="请输入（可备注需要但系统中没有的维度和统计粒度，或其他需要备注的信息）"
        />
    </a-form-item>
</template>

<style lang="scss" scoped></style>